<template>
  <div class="user">
    <div class="tools">
      <Search
        @toSearch="toSearch"
        :placeholder1="placeholder1"
        @reFresh="initList"
      ></Search>
    </div>
    <router-view @reFresh="initList"></router-view>
    <Table
      v-if="refresh"
      :list-data="List"
      @reFresh="initList"
      @sortChange="sortChange"
      @delete="deleteRow"
    >
      <template #column>
        <el-table-column
          prop="nickName"
          label="昵称"
          min-width="180"
          align="center"
        >
          <template #default="scope">
            <span class="avatar">
              <img :src="scope.row.avatarUrl" />
            </span>
            <span class="userName">{{ scope.row.nickName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="openid"
          label="微信标识ID"
          min-width="280"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="country"
          label="国家"
          min-width="120"
          align="center"
        >
          <template #default="scope">
            <span>{{ scope.row.country || "暂无" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="province"
          label="省份"
          min-width="120"
          align="center"
        >
          <template #default="scope">
            <span>{{ scope.row.province || "暂无" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="city"
          label="城市"
          min-width="120"
          align="center"
        >
          <template #default="scope">
            <span>{{ scope.row.city || "暂无" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="系统角色"
          min-width="120"
          align="center"
          :filters="[
            { text: '访客', value: 0 },
            { text: '业主', value: 1 },
            { text: '租客', value: 2 },
          ]"
          :filter-multiple="false"
          :filter-method="filterTag"
          filter-placement="bottom-end"
        >
          <template #default="scope">
            <el-tag type="info" v-if="scope.row.role === 0">
              <span>访客</span>
            </el-tag>
            <el-tag v-if="scope.row.role === 1">
              <span>业主</span>
            </el-tag>
            <el-tag type="success" v-if="scope.row.role === 2">
              <span>租客</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          header-align="center"
          align="center"
          min-width="180"
        >
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="deleteRow(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </template>
    </Table>
    <div style="height: 50px">
      <Pagination
        :lockNxt="lockNxt"
        @prePage="prePage"
        @nxtPage="nxtPage"
      ></Pagination>
    </div>
  </div>
</template>

<script lang="ts">
import { nextTick, ref, Ref, watch } from "vue";
import router from "../router/index";
import { User } from "../types/listTypes";
import { ElMessage, ElMessageBox } from "element-plus";
import type { TableColumnCtx } from "element-plus/es/components/table/src/table-column/defaults";
import request from "../axios/index";
import Search from "../components/Search.vue";
import Table from "../components/Table.vue";
import Pagination from "../components/Pagination.vue";
import { mainStore } from "../store/index";

export default {
  name: "User",
  components: {
    Search,
    Table,
    Pagination,
  },
  setup() {
    const store = mainStore();

    //控制刷新显示
    let refresh: Ref<boolean> = ref(true);
    //定义单页数量
    let pageCount: Ref<number> = ref(0);
    //定义锁定下页
    let lockNxt: Ref<boolean> = ref(false);

    //刷新触发函数
    function toFresh(): void {
      refresh.value = false;
      nextTick(() => {
        refresh.value = true;
      });
    }
    //删除信息
    function deleteRow(index: number, row: User): void {
      ElMessageBox.confirm("是否确认删除该信息")
        .then(() => {
          request
            .post("/admin/user/userDelete", {
              userId: row.id,
            })
            .then((res) => {
              if (res.data.code === 200) {
                ElMessage({
                  message: res.data.message,
                  type: "success",
                });
                toFresh();
              } else {
                ElMessage({
                  message: res.data.message,
                  type: "error",
                });
              }
            });
        })
        .catch((err) => {
          ElMessage("已取消删除");
        });
    }
    //触发上一页
    function prePage(currentPage: number) {
      ElMessage(`第${currentPage}页`);
      getList(pageCount.value, currentPage);
    }
    //触发下一页
    function nxtPage(currentPage: number) {
      ElMessage(`第${currentPage}页`);
      getList(pageCount.value, currentPage);
    }
    //发起搜索请求
    async function toSearch(input) {
      try {
        const res = await request.get("/admin/user/searchUser", {
          params: {
            keywords: input.keyWords,
          },
        });
        List.value = res.data.data;
      } catch (e) {
        console.error(e);
      }
    }

    //初始化组件内容
    const placeholder1: string = "请输入用户昵称";

    //初始化公告列表
    let List: Ref<User[]> = ref([]);

    //初始化列表请求
    function initList(pc: number) {
      pageCount.value = pc;
      getList();
    }

    //列表请求
    function getList(count: number = pageCount.value, page: number = 1): void {
      request
        .get("/admin/user/userList", {
          params: {
            count: count,
            page: page,
          },
        })
        .then((res) => {
          List.value = res.data.data;
        });
    }
    //用户角色筛选
    const filterTag = (value: number, row: User): boolean => {
      return row.role === value;
    };
    const filterHandler = (
      value: string,
      row: User,
      column: TableColumnCtx<User>
    ) => {
      const property = column["property"];
      return row[property] === value;
    };
    //表格编辑按钮
    function handleEdit(index, row) {
      store.addCacheData(row);
      router.push("/smart-e/admin/index/user/EditUser");
    }

    //监听页面长度
    watch(
      () => List.value.length,
      (newVal, oldVal) => {
        if (newVal < pageCount.value) {
          lockNxt.value = true;
        } else {
          lockNxt.value = false;
        }
      },
      {
        immediate: true,
      }
    );

    return {
      refresh,
      placeholder1,
      List,
      getList,
      filterTag,
      filterHandler,
      deleteRow,
      toSearch,
      prePage,
      nxtPage,
      initList,
      lockNxt,
      handleEdit,
    };
  },
};
</script>

<style scoped>
.user {
  position: relative;
  width: 98%;
  min-height: 520px;
  background-color: #fff;
}
.tools {
  width: 100%;
  height: 50px;
  overflow: hidden;
}
.avatar img {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}
.userName {
  display: block;
  float: right;
  width: 70px;
  height: 30px;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
